<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>移动选项</title>
    <script>
        function move(fromId, toId) {
            let fromChild = document.getElementById(fromId);
            let toChild = document.getElementById(toId);
            // 遍历fromChild中所有选项
            // 当fromChild中元素移动到toChild中之后,fromChild中元素下标会发生变化
            // 因此此处必须使用降序
            for (let i = fromChild.length - 1; i >= 0; i--) {
                // 取出当前迭代的选项
                let op = fromChild.options[i];
                // 判断当前选项是否被选中
                if (op.selected) {
                    // 如果选中了,则将该选项移动到toChild中
                    // 当下拉列中的某个选项被赋值给另一个下拉列,则当前下拉列自动清除已赋值过的选项
                    toChild[toChild.length] = op;
                    // 将移动过去的选项设置为未选中状态
                    toChild[toChild.length - 1].selected = false;
                }
            }
        }

        function moveAll(fromId, toId) {
            let fromChild = document.getElementById(fromId);
            let toChild = document.getElementById(toId);
            // for (let i = fromChild.length - 1; i >= 0; i--) {
            //     let op = fromChild.options[i];
            //     // 移动所有与移动选中选项的区别在于:不需要判断是否选中
            //     toChild[toChild.length] = op;
            //     toChild[toChild.length - 1].selected = false;
            // }
            let index = fromChild.length;
            for (let i = 0; i < index; i++) {
                let op = fromChild.options[0];
                // 移动所有与移动选中选项的区别在于:不需要判断是否选中
                toChild[toChild.length] = op;
                toChild[toChild.length - 1].selected = false;
            }
        }
    </script>
</head>
<body>
<table>
    <tr>
        <td>
            <select id="s1" multiple style="width: 100px;height: 120px;">
                <option value="1">admin</option>
                <option value="2">alice</option>
                <option value="3">jack</option>
                <option value="4">lucy</option>
                <option value="5">tom</option>
            </select>
        </td>
        <td>
            <input type="button" value="&nbsp;-->" onclick="move('s1','s2')"><br>
            <input type="button" value="->>" onclick="moveAll('s1','s2')"><br>
            <input type="button" value="<--&nbsp;" onclick="move('s2','s1')"><br>
            <input type="button" value="<<-" onclick="moveAll('s2','s1')"><br>
        </td>
        <td>
            <select id="s2" multiple style="width: 100px;height: 120px;">

            </select>
        </td>
    </tr>
</table>
</body>
</html>